package com.expdatacloud.service.impl;

import com.expdatacloud.dto.ApiResponse;
import com.expdatacloud.dto.BadSkuOverThreeDaysDto;
import com.expdatacloud.dto.OverdueMaterialDto;
import com.expdatacloud.dto.UnQualifiedQualityDto;
import com.expdatacloud.mapper.IqcDetectionHistoryMapper;
import com.expdatacloud.mapper.ReportsMapper;
import com.expdatacloud.service.ReportsService;
import com.expdatacloud.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jie
 * @date 2019/12/1 -16:16
 */
@Service
public class ReportsServiceImpl implements ReportsService {

    @Autowired
    private ReportsMapper reportsMapper;
    @Autowired
    private IqcDetectionHistoryMapper iqcDetectionHistoryMapper;


    @Override
    public List<ReceivingBoardVo> receivingBoardList() {
        return reportsMapper.receivingBoardList();
    }

    @Override
    public List<UnQualifiedQualityVo> unQualifiedQualityList(UnQualifiedQualityDto unQualifiedQualityDto) {
        unQualifiedQualityDto. setLoc("STAGE-OK");
        return reportsMapper.unQualifiedQualityList(unQualifiedQualityDto);
    }

    @Override
    public List<UnQualifiedQualityVo> qualifiedQualityList(UnQualifiedQualityDto unQualifiedQualityDto) {
        unQualifiedQualityDto. setLoc("STAGE-NG");
        return reportsMapper.unQualifiedQualityList(unQualifiedQualityDto);
    }

    @Override
    public List<ReceivingReconciliationVo> reconciliationList(String startTime, String endTime) {
        return reportsMapper.reconciliationList(startTime, endTime);
    }

    @Override
    public List<IqcHistoryReconciliationVo> iqcHistoryReconciliationList(String startTime, String endTime) {
        return reportsMapper.iqcHistoryReconciliationList(startTime, endTime);
    }

    @Override
    public List<SuppliedMaterialsDailyVo> suppliedMaterialsList(SuppliedMaterialsDailyVo suppliedMaterialsDailyVo) {
        String[] modelKeyArrays = suppliedMaterialsDailyVo.getModelKeyStr() != null ?
                suppliedMaterialsDailyVo.getModelKeyStr().split(",") : null;
        if (modelKeyArrays != null) {
            if ((modelKeyArrays.length == 1) && "".equals(modelKeyArrays[0])) {
                modelKeyArrays = null;
            }
        }

        String[] decideWayArrays = suppliedMaterialsDailyVo.getDecideWayStr() != null ?
                suppliedMaterialsDailyVo.getDecideWayStr().split(",") : null;
        if (decideWayArrays != null) {
            if ((decideWayArrays.length == 1) && "".equals(decideWayArrays[0])) {
                decideWayArrays = null;
            }
        }
        suppliedMaterialsDailyVo.setModelKeys(modelKeyArrays);
        suppliedMaterialsDailyVo.setDecideWays(decideWayArrays);
        return reportsMapper.suppliedMaterialsList(suppliedMaterialsDailyVo);
    }

    @Override
    public Map<String, Object> suppliedMaterialsCheckWeekReportList(String startTime, String endTime, String modelKey, String shipper)
            throws ParseException {
        String year = null;
        if (startTime != null) {
            year = startTime.split("-")[0];
        }
        Map<String, Object> baseMap = new HashMap<>();
        //转换时间为自然周
        int start = StringUtils.isEmpty(startTime) ? 1 : transformDateToWeek(startTime);
        int end = StringUtils.isEmpty(endTime) ? 52 : transformDateToWeek(endTime);

        List<SuppliedMaterialsCheckWeekReportVo> suppliedMaterialsCheckWeekReportList = new ArrayList<>();
        String[] modelKeyArrays = modelKey != null ? modelKey.split(",") : null;
        if (modelKeyArrays != null) {
            if ((modelKeyArrays.length == 1) && "".equals(modelKeyArrays[0])) {
                modelKeyArrays = null;
            }
        }
        List<Integer> weekList = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            SuppliedMaterialsCheckWeekReportVo suppliedMaterialsCheckWeekReportVo2 = reportsMapper.
                    suppliedMaterialsCheckWeekReport(year, i, modelKeyArrays, "", shipper);
            if (suppliedMaterialsCheckWeekReportVo2 != null) {
                weekList.add(i);
                suppliedMaterialsCheckWeekReportList.add(suppliedMaterialsCheckWeekReportVo2);
            }
        }
        baseMap.put("suppliedMaterialsCheckWeekReportList", suppliedMaterialsCheckWeekReportList);
        baseMap.put("weekList", weekList);
        return baseMap;
    }

    @Override
    public Map<String, Object> suppliedMaterialsCheckWeekByUDF8ReportList(String startTime, String endTime, String modelKey, String shipper) throws ParseException {
        String year = null;
        if (startTime != null) {
            year = startTime.split("-")[0];
        }
        Map<String, Object> baseMap = new HashMap<>();
        //转换时间为自然周
        int start = StringUtils.isEmpty(startTime) ? 1 : transformDateToWeek(startTime);
        int end = StringUtils.isEmpty(endTime) ? 52 : transformDateToWeek(endTime);

        List<SuppliedMaterialsCheckWeekReportVo> suppliedMaterialsCheckWeekReportList = new ArrayList<>();
        //周的集合
        List<Integer> weekList = new ArrayList<>();
        //物料大类集合
        List<String> udf8List = reportsMapper.getUdf8List();
        String[] modelKeyArrays = modelKey != null ? modelKey.split(",") : null;
        if (modelKeyArrays != null) {
            if ((modelKeyArrays.length == 1) && "".equals(modelKeyArrays[0])) {
                modelKeyArrays = null;
            }
        }
        for (int i = start; i <= end; i++) {
            for (String udf8 : udf8List) {
                SuppliedMaterialsCheckWeekReportVo suppliedMaterialsCheckWeekReportVo2 = reportsMapper.suppliedMaterialsCheckWeekReport(year,
                        i, modelKeyArrays, udf8 == null ? "" : udf8, shipper);
                if (suppliedMaterialsCheckWeekReportVo2 != null) {
                    suppliedMaterialsCheckWeekReportList.add(suppliedMaterialsCheckWeekReportVo2);
                }
            }
            weekList.add(i);
        }
        List<SuppliedMaterialsCheckWeekReportVo> sumList = new ArrayList();
        for (String udf8 : udf8List) {
            int sum = suppliedMaterialsCheckWeekReportList.stream()
                    .filter(suppliedMaterialsCheckWeekReportVo -> udf8.equals(suppliedMaterialsCheckWeekReportVo.getUdf8()))
                    .mapToInt(suppliedMaterialsCheckWeekReportVo -> suppliedMaterialsCheckWeekReportVo.getSalesReturnQty()).sum();
            SuppliedMaterialsCheckWeekReportVo suppliedMaterialsCheckWeekReportVo = new SuppliedMaterialsCheckWeekReportVo();
            suppliedMaterialsCheckWeekReportVo.setSumQty(sum);
            suppliedMaterialsCheckWeekReportVo.setUdf8(udf8);
            sumList.add(suppliedMaterialsCheckWeekReportVo);
        }
        baseMap.put("suppliedMaterialsCheckWeekReportList", suppliedMaterialsCheckWeekReportList);
        baseMap.put("weekList", weekList);
        baseMap.put("sumList", sumList);
        baseMap.put("udf8List", udf8List);
        return baseMap;
    }

    @Override
    public Map<String, Object> suppliedMaterialsCheckMonthReport(String startTime, String endTime, String modelKey, String shipper) {

        int startYear = Integer.parseInt(startTime.split("-")[0]);
        int endYear = Integer.parseInt(endTime.split("-")[0]);


        Map<String, Object> baseMap = new HashMap<>();
        List<SuppliedMaterialsCheckMonthReportVo> suppliedMaterialsCheckMonthReportVoList = new ArrayList<>();
        List<Integer> monthList = new ArrayList<>();

        //获取间隔的月数
        int monthCount = 12;
        if (StringUtils.isNotEmpty(startTime) || StringUtils.isNotEmpty(endTime)) {
            monthCount = reportsMapper.getMonthCount(endTime.substring(0, 7), startTime.substring(0, 7));
        }

        //获取起始年的月份
        int startMonth1 = 1;
        if (StringUtils.isNotEmpty(startTime)) {
            startMonth1 = reportsMapper.getStartMonth(startTime);
        }

        String[] modelKeyArrays = modelKey != null ? modelKey.split(",") : null;
        if (modelKeyArrays != null) {
            if ((modelKeyArrays.length == 1) && "".equals(modelKeyArrays[0])) {
                modelKeyArrays = null;
            }
        }

        //如果有输入时间
        int end = startMonth1 + monthCount;
        for (int year = startYear; year <= endYear; year++) {
            //获取一月份间隔
            for (int month = startMonth1; month <= end; month++) {

                SuppliedMaterialsCheckMonthReportVo suppliedMaterialsCheckMonthReportVo = reportsMapper.suppliedMaterialsCheckMonthReport(year, month, modelKeyArrays, shipper);
                if (suppliedMaterialsCheckMonthReportVo != null) {
                    suppliedMaterialsCheckMonthReportVoList.add(suppliedMaterialsCheckMonthReportVo);
                }
                monthList.add(month);
                if (month == 12) {

                    end = (startMonth1 + monthCount) > 12 ? (startMonth1 + monthCount) - 12 : (startMonth1 + monthCount);
                    startMonth1 = 1;
                    break;
                }
            }
        }

        Map<String, Object> sumMap = new HashMap<>();
        double checkQtySum = 0;
        double okQtySum = 0;
        double ngQtySum = 0;
        String percentOfPassSum = "0";

        for (SuppliedMaterialsCheckMonthReportVo suppliedMaterialsCheckMonthReportVo : suppliedMaterialsCheckMonthReportVoList) {
            checkQtySum += suppliedMaterialsCheckMonthReportVo.getCheckQty();
            okQtySum += suppliedMaterialsCheckMonthReportVo.getOkQty();
            ngQtySum += suppliedMaterialsCheckMonthReportVo.getNgQty();
        }
        DecimalFormat df = new DecimalFormat("#.00");
        if (checkQtySum != 0) {
            percentOfPassSum = df.format(okQtySum / checkQtySum * 100);
        }

        sumMap.put("checkQtySum", checkQtySum);
        sumMap.put("okQtySum", okQtySum);
        sumMap.put("ngQtySum", ngQtySum);
        sumMap.put("percentOfPassSum", percentOfPassSum);

        baseMap.put("suppliedMaterialsCheckMonthReportVoList", suppliedMaterialsCheckMonthReportVoList);
        baseMap.put("monthList", monthList);
        baseMap.put("sumMap", sumMap);
        return baseMap;
    }

    @Override
    public List<SuppliedMaterialsBadTop10Vo> suppliedMaterialsBadTop10List(String flag, String time) {

        List<SuppliedMaterialsBadTop10Vo> suppliedMaterialsBadTop10VoList = new ArrayList<>();

        if (StringUtils.isNotEmpty(time)) {
            String year = time.split("-")[0];
            String month = time.split("-")[1];

            suppliedMaterialsBadTop10VoList = reportsMapper.suppliedMaterialsBadTop10VoList(flag, year, month);
        } else {
            suppliedMaterialsBadTop10VoList = reportsMapper.suppliedMaterialsBadTop10VoList(flag, null, null);
        }

        // 获取大集合里面的所有供应商编码
        List<String> supplierKeyList = suppliedMaterialsBadTop10VoList.stream().map(SuppliedMaterialsBadTop10Vo::getSupplierKey)
                .collect(Collectors.toList());

        // 获取大集合里面重复供应商编码的数据
        Map<String, List<String>> collect = supplierKeyList.stream().collect(Collectors.groupingBy(x -> x));
        List<String> redoSupplierKeyList = collect.values().stream().filter(x -> x.size() > 1).flatMap(Collection::stream).distinct().collect(Collectors.toList());

        List<SuppliedMaterialsBadTop10Vo> resultList = new ArrayList<>(suppliedMaterialsBadTop10VoList);

        for (SuppliedMaterialsBadTop10Vo suppliedMaterialsBadTop10Vo : suppliedMaterialsBadTop10VoList) {

            for (String supplierKey : redoSupplierKeyList) {
                // 在大集合里面剔除编码相同物料为空的
                if (suppliedMaterialsBadTop10Vo.getSupplierKey().equals(supplierKey) && StringUtils.isEmpty(suppliedMaterialsBadTop10Vo.getSkuTypes())) {
                    resultList.remove(suppliedMaterialsBadTop10Vo);
                }
            }

        }

        //如果没有10个供应商直接返回 resultList
        if (resultList.size() < 10) {
            return resultList;
        }else{
            return resultList.subList(0,10);
        }
    }

    @Override
    public int updateTop10(SuppliedMaterialsBadTop10Vo suppliedMaterialsBadTop10Vo) {

        return reportsMapper.updateTop10(suppliedMaterialsBadTop10Vo);
    }


    /**
     * 转换时间为自然周
     */
    @Override
    public int transformDateToWeek(String time) throws ParseException {
        if (StringUtils.isEmpty(time)) {
            return -1;
        }
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = format.parse(time);
        calendar.setTime(date);
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }

    @Override
    public List<OverdueMaterialVo> getOverdueMaterialList(OverdueMaterialDto overdueMaterialDto) {

        String[] modelKeyArray  = null;
        if (StringUtils.isNotEmpty(overdueMaterialDto.getModelKey())) {
            modelKeyArray  = overdueMaterialDto.getModelKey().split(",");
            overdueMaterialDto.setModelKeys(modelKeyArray);
        }

        return reportsMapper.getOverdueMaterial(overdueMaterialDto);
    }


    @Override
    public List<BadSkuThreeDaysVo> getBadSkuOverThreeDays(BadSkuOverThreeDaysDto badSkuOverThreeDaysDto) {
        //ApiResponse<List<BadSkuThreeDaysVo>> apiResponse = new ApiResponse<>();

        List<BadSkuThreeDaysVo> badSkuThreeDaysVoList = reportsMapper.getBadSkuOverThreeDays(badSkuOverThreeDaysDto);

        return badSkuThreeDaysVoList;
//        List<NewitrnVo> newitrnVoList = reportsMapper.getNewitrn(badSkuOverThreeDaysDto);
//
//        for (InvLotLocVo invLotLocVo : badSkuOverThreeDaysList) {
//
//            Double lotlocidQty = invLotLocVo.getQty();
//            for (NewitrnVo newitrnVo : newitrnVoList) {
//
//                if (newitrnVo.getSku().equals(invLotLocVo.getSku())
//                        && newitrnVo.getStorerkey().equals(invLotLocVo.getStorerkey())
//                        && newitrnVo.getToloc().equals(invLotLocVo.getLoc())
//                        && newitrnVo.getLot().equals(invLotLocVo.getLot())) {
//
//                    BadSkuThreeDaysVo badSkuThreeDaysVo = new BadSkuThreeDaysVo();
//                    badSkuThreeDaysVo.setStorerkey(invLotLocVo.getStorerkey());
//                    badSkuThreeDaysVo.setSku(invLotLocVo.getSku());
//                    badSkuThreeDaysVo.setDescr(invLotLocVo.getDescr());
//                    badSkuThreeDaysVo.setDefault6(invLotLocVo.getDefault6());
//
//                    if ("KG".equals(invLotLocVo.getDefault7())) {
//                        badSkuThreeDaysVo.setDefault7("G");
//                    } else if ("L".equals(invLotLocVo.getDefault7())) {
//                        badSkuThreeDaysVo.setDefault7("ML");
//                    } else {
//                        badSkuThreeDaysVo.setDefault7(invLotLocVo.getDefault7());
//                    }
//
//                    badSkuThreeDaysVo.setQty(invLotLocVo.getQty());
//                    badSkuThreeDaysVo.setLottable01(invLotLocVo.getLottable01());
//                    if("H001".equals(invLotLocVo.getLottable01())||"Q001".equals(invLotLocVo.getLottable01())){
//                        badSkuThreeDaysVo.setLottable02(invLotLocVo.getLottable02());
//                    }
//
//                    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd ");
//                    //如果库存数量小于事务第一条数量
//                    if (lotlocidQty < newitrnVo.getQty()) {
//                        int days = (int) ((System.currentTimeMillis() - newitrnVo.getEffectivedate().getTime()) / (1000 * 3600 * 24));
//                        if (days >= 3) {
//                            badSkuThreeDaysVo.setDocumentDate( format.format(newitrnVo.getEffectivedate()));
//                            badSkuThreeDaysVo.setDays(days);
//                            badSkuThreeDaysVoList.add(badSkuThreeDaysVo);
//                            break;
//                        }
//
//                    } else {
//
//                        if (lotlocidQty < 0) {
//                            break;
//                        }
//                        lotlocidQty = lotlocidQty - newitrnVo.getQty();
//
//                        int days = (int) ((System.currentTimeMillis() - newitrnVo.getEffectivedate().getTime()) / (1000 * 3600 * 24));
//                        if (days >= 3) {
//                            badSkuThreeDaysVo.setDocumentDate( format.format(newitrnVo.getEffectivedate()));
//                            badSkuThreeDaysVo.setDays(days);
//                            badSkuThreeDaysVoList.add(badSkuThreeDaysVo);
//                        }
//                    }
//
//                }
//            }
//        }
//
//        toPage(page, limit, apiResponse, badSkuThreeDaysVoList);
//        return apiResponse;
    }

    private void toPage(int page, int limit, ApiResponse<List<BadSkuThreeDaysVo>> apiResponse, List<BadSkuThreeDaysVo> badSkuThreeDaysVoList) {
        int size = limit - 1;
        if (size > badSkuThreeDaysVoList.size()) {
            size = badSkuThreeDaysVoList.size();
        }

        int start = (page - 1) * size;
        int end = page * size;

        if (end > badSkuThreeDaysVoList.size()) {
            end = badSkuThreeDaysVoList.size();
        }
        apiResponse.setCount(badSkuThreeDaysVoList.size());
        badSkuThreeDaysVoList = badSkuThreeDaysVoList.subList(start, end);
        apiResponse.setData(badSkuThreeDaysVoList);
    }
}
